<template>

  <span @click="dialogVisible = true">
    <slot></slot>
  </span>

  <el-dialog v-model="dialogVisible" class="w-4/12" draggable title="请上传头像">
    <el-upload
      :before-upload="beforeAvatarUpload"
      :headers="headers"
      :multiple="false"
      :on-success="handleSuccess"
      action="http://localhost:7345/api/upload"
      list-type="picture-card"
    >
      <el-icon class="avatar-uploader-icon">
        <Plus />
      </el-icon>
    </el-upload>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="whenCancel">取消</el-button>
        <el-button class="bg-green-600" type="success" @click="whenConfirm">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { changeAvatar } from "@/utils/api/user";
import { getToken } from "@/utils/auth";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
import { ref } from "vue";

const dialogVisible = ref(false);

let imageId = ref("");

const headers = {
  Authorization: getToken()
};

const whenCancel = () => {
  imageId.value = "";
  dialogVisible.value = false;

};
const whenConfirm = () => {
  changeAvatar(imageId.value.toString()).then(() => {
    ElMessage.success("头像修改成功");
    dialogVisible.value = false;
  }).catch((err) => {
    ElMessage.error(err);
  });
  dialogVisible.value = false;

};


const handleSuccess: UploadProps["onSuccess"] = (response, uploadFile, uploadFiles) => {
  if (response.code === 200) {
    ElMessage.success("头像上传成功");
    imageId.value = response.data.file_id;
  } else {
    ElMessage.error("头像上传失败");
  }

};


const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("头像文件必须是JPG格式");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("头像文件不能大于 2MB!");
    return false;
  }
  return true;
};


</script>

<style scoped>

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

</style>
